package com.zzy.controller;

import com.zzy.datagridlist.Datagrid;
import com.zzy.model.User;
import com.zzy.service.UserService;
import com.zzy.service.UtilService;
import com.zzy.util.AjaxMsg;
import com.zzy.util.StatusCode;
import com.zzy.util.UtilJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Controller()
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UtilService utilService;

    /**跳转到列表页面*/
    @RequestMapping(value="index")
    public String index(HttpServletRequest request, HttpServletResponse response){
       return "page/user/user_index";
    }
    /**获取数据表格内容*/
    @RequestMapping(value="gird")
    @ResponseBody
    public void gird(HttpServletRequest request, HttpServletResponse response){
        Datagrid.list(request,response,User.class,utilService);
    }


    /**跳转到详情页面*/
    @RequestMapping(value="load")
    public String load(HttpServletRequest request, HttpServletResponse response){
        String id = request.getParameter("id");
        if(id!=null){
            User user = userService.getByID(id);
            request.setAttribute("model",user);
            request.setAttribute("load",request.getParameter("load"));
        }
        return   "page/user/user_detail";
    }

    /**添加或者修改*/
    @RequestMapping(value="opt")
    @ResponseBody
    public void addOrUpdate(User model, HttpServletRequest request, HttpServletResponse response){
        if(model!=null && model.getId()!=null && model.getId().trim().equals("")){//保证传递的ID不是空值 而是null
            model.setId(null);
        }
        UtilJson.jsonPrintln(userService.saveOrUpdate(model),response);
    }

    /**删除*/
    @RequestMapping(value="delete")
    @ResponseBody
    public void delete(String id,HttpServletRequest request, HttpServletResponse response){
        UtilJson.jsonPrintln(userService.del(id),response);;
    }

    /**验证用户是否存在*/
    @RequestMapping(value="check")
    @ResponseBody
    public void check(HttpServletRequest request, HttpServletResponse response){
        String userName = request.getParameter("userName");
        UtilJson.jsonPrintModel(AjaxMsg.returnAjaxMsg(StatusCode.SUCCESS,userService.isExist(userName)),response);
    }
}
